<template>
  <div class="container">
    <h1>测试幂等性下单</h1>
    <button @click="getToken">获取幂等Token</button>
    <p>Token: {{ token }}</p>

    <button @click="submitOrder" :disabled="!token">提交订单</button>

    <p v-if="result">返回结果：{{ result }}</p>
  </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";

const token = ref("");
const result = ref("");

const getToken = async () => {
  try {
    const res = await axios.get("http://localhost:8080/app/idempotent/createToken");
    token.value = res.data.data; // 后端返回的 token
    result.value = "";
  } catch (err) {
    console.error(err);
    result.value = "获取token失败";
  }
};

const submitOrder = async () => {
  if (!token.value) {
    result.value = "请先获取 token";
    return;
  }

  try {
    const res = await axios.post(
      "http://localhost:8080/app/orders/create",
      {
        orderName: "测试订单",
        orderPrice: 100
      },
      {
        headers: {
          formToken: token.value // 带上幂等token
        }
      }
    );
    result.value = JSON.stringify(res.data);
  } catch (err) {
    console.error(err);
    if (err.response) {
      result.value = JSON.stringify(err.response.data);
    } else {
      result.value = "请求失败";
    }
  }
};
</script>

<style scoped>
.container {
  max-width: 600px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 10px;
}
button {
  margin: 10px 0;
  padding: 8px 16px;
}
</style>